<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="店铺" prop="shopId">
        <el-select size="small" placeholder="请选择店铺" clearable filterable v-model="queryParams.shopId" >
          <el-option v-for="item in shops" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="平台商品" prop="refspuid">
        <el-select v-model="queryProductId" @change="takeQueryPro" placeholder="请选择平台商品" style="width: 600px;" clearable filterable>
          <el-option
            v-for="item in products"
            :key="item.id"
            :label="item.title + '[' + item.status + ']'"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['d3:protosp:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['d3:protosp:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['d3:protosp:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['d3:protosp:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="protospList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="店铺名称" align="center" prop="shopName" width="150"/>
      <el-table-column label="货品标题" align="center" prop="title" width="250" />
      <el-table-column label="sku规格属性" align="center" prop="standards" width="240" />
      <el-table-column label="ERP系统物料名称" align="center" prop="spName" />
      <el-table-column label="数量" align="center" prop="num" width="40" />
      <el-table-column label="单价" align="center" prop="price" width="45" />
      <el-table-column label="操作人" align="center" prop="nickName" width="120"/>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['d3:protosp:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.isToSellform != 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['d3:protosp:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对应关系对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" inline label-width="110px">
        <el-form-item label="平台店铺" prop="shopId">
          <el-select v-model="form.shopId" placeholder="请选择平台店铺" size="small" style="width: 500px;" clearable filterable>
            <el-option
              v-for="item in shops"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="平台商品" prop="refspuid">
          <el-select v-model="formProductId" @change="takeProduct" size="small" placeholder="请选择平台商品" style="width: 500px;" clearable filterable>
            <el-option
              v-for="item in products"
              :key="item.id"
              :label="item.title + '[' + item.status + ']'"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <template v-if="formProductId">
          <el-form-item label="平台spuId" label-width="110px">
            <el-input v-model="form.refspuid" readonly size="small" clearable style="width: 190px;" />
          </el-form-item>
          <el-form-item label="平台skuId" label-width="110px">
            <el-input v-model="form.refskuid" readonly size="small" clearable style="width: 190px;" />
          </el-form-item>
          <el-form-item label="sku规格属性" label-width="110px">
            <el-input v-model="form.standards" type="textarea" readonly size="small" clearable style="width: 500px;" />
          </el-form-item>
        </template>
        <el-form-item label="Erp平台品种" prop="erpProductId" label-width="110px">
          <el-select v-model="erpProductId" placeholder="请选择Erp平台品种" size="small" style="width: 500px;" filterable clearable>
            <el-option
              v-for="item in erpProducts"
              :key="item.guid"
              :label="item.productname"
              :value="item.guid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Erp平台物料" prop="spId" label-width="110px">
          <el-select v-model="form.spId" @change="takeSpec" placeholder="请选择Erp平台物料" size="small" style="width: 500px;" filterable clearable>
            <el-option
              v-for="item in specs"
              :key="item.autoId"
              :label="item.name"
              :value="item.autoId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="num" label-width="110px">
          <el-input v-model="form.num" placeholder="请输入数量" size="small" clearable style="width: 500px;" />
        </el-form-item>
        <el-form-item label="单价" prop="price" label-width="110px">
          <el-input v-model="form.price" placeholder="请输入单价" size="small" clearable style="width: 500px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProtosp, getProtosp, delProtosp, addProtosp, updateProtosp, exportProtosp } from "@/api/d3/protosp";
import { listShop } from "@/api/d3/shop";
import { listProduct } from "@/api/d3/product";
import { findSpecificationList, findProductList } from "@/api/public";

export default {
  name: "Protosp",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品对应关系表格数据
      protospList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopId: null,
        refspuid: null,
        refskuid: null,
        title: null,
        standards: null,
        spId: null,

        spName: null,
        num: null,
        price: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        shopId: [
          { required: true, message: "请选择平台店铺", trigger: "change" }
        ],
        refspuid: [
          { required: true, message: "请选择平台商品", trigger: "change" }
        ],
        spId: [
          { required: true, message: "请选择Erp平台物料", trigger: "change" }
        ],
        num: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "单价不能为空", trigger: "blur"},
          { pattern: /^\+?[1-9]\d*$/, message: '请输入大于0的正整数'}
        ],
      },
      shops: [],
      products: [],
      erpProducts: [],
      specs: [],
      queryProductId: '',
      erpProductId: '',
      formProductId: ''
    };
  },
  watch: {
    'queryParams.shopId':function(val,oldVal){
      this.getProducts(val);
    },
    'form.shopId': function (id) {
      if (!id) return;
      this.getProducts(id);
    },
    'erpProductId': function(val) {
      if (!val) return;
      this.getErpSpecs(val);
      this.form.childspid = '';
    }
  },
  created() {
    this.getShops();
    this.getProducts();
    this.getErpProducts();
    this.getList();
  },
  methods: {
    takeQueryPro(id) {
      const queryProduct = this.products.find(item => item.id == id);
      this.queryParams.refspuid = queryProduct.refspuid;
      this.queryParams.refskuid = queryProduct.refskuid;
    },
    takeProduct(id) {
      const product = this.products.find(item => item.id == id);
      if (!product) return;
      this.form.refspuid = product.refspuid;
      this.form.refskuid = product.refskuid;
      this.form.title = product.title;
      this.form.standards = product.standards;
    },
    takeSpec(id) {
      console.log('id:', id)
      const spec = this.specs.find(item => item.autoId == id);
      if (!spec) return;
      this.form.spName = spec.name;
    },
    /** 查询d3店铺列表 */
    getShops() {
      listShop().then(response => {
        this.shops = response.rows;
      });
    },
    /** 查询d3店铺的商品列表 */
    getProducts(pid = '') {
      listProduct({shopId: pid}).then(response => {
        this.products = response.rows;
      });
    },
    getErpProducts() {
      findProductList().then(response => {
        this.erpProducts = response.data;
        // console.log(response.data);
      });
    },
    /** 查询erp规格列表 */
    getErpSpecs(productId) {
      findSpecificationList({productguid: productId}).then(response => {
        this.specs = response.data;

      });
    },
    /** 查询商品对应关系列表 */
    getList() {
      this.loading = true;
      listProtosp(this.queryParams).then(response => {
        this.protospList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shopId: null,
        refspuid: null,
        refskuid: null,
        title: null,
        standards: null,
        spId: null,
        spName: null,
        num: null,
        price: null
      };
      this.erpProductId = null;
      this.formProductId = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品对应关系";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProtosp(id).then(response => {
        this.form = response.data;
        // this.formProductId = this.products.find(item => item.)
        this.open = true;
        this.title = "修改商品对应关系";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProtosp(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProtosp(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProtosp(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品对应关系数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportProtosp(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
